package top.jfunc.json.impl;

import top.jfunc.json.Json;
import top.jfunc.json.JsonArray;
import top.jfunc.json.JsonException;
import top.jfunc.json.JsonObject;
import top.jfunc.json.impl.parse.JSONParser;
import top.jfunc.json.utils.JsonUtil;

import java.util.List;
import java.util.Map;

/**
 * @author xiongshiyan at 2018/6/11
 */
public class JSONArray extends BaseListJSONArray {
    public JSONArray(List<Object> list){
        super(list);
    }
    public JSONArray(){
        super();
    }
    public JSONArray(String arrayString){
        super(arrayString);
    }

    @Override
    public JsonObject getJsonObject(int index) {
        assertIndex(index , size());
        Object opt = list.get(index);
        if(opt instanceof Map){
            return new JSONObject((Map<String, Object>) opt);
        }
        return (JsonObject) opt;
    }

    @Override
    public JsonArray getJsonArray(int index) {
        assertIndex(index , size());
        Object opt = list.get(index);
        if(opt instanceof List){
            return new JSONArray((List<Object>) opt);
        }
        return (JsonArray) opt;
    }

    @Override
    public JsonArray parse(String jsonString) {
        super.list = str2List(jsonString);
        return this;
    }

    @Override
    public String toString() {
        return JsonUtil.listToStr(super.list);
    }

    @Override
    public List<Object> str2List(String arrayString) {
        JSONParser jsonParser = new JSONParser();
        Json jsonObject = jsonParser.fromJSON(arrayString);
        return (List<Object>)jsonObject.unwrap();
    }



    @Override
    public Json toJson(Object o) {
        if(o instanceof List){
            return new JSONArray((List<Object>) o);
        }
        if(o instanceof Map){
            return new JSONObject((Map<String, Object>) o);
        }
        try {
            return (Json) o;
        } catch (Exception e) {
            throw new JsonException("不能将非Json的对象转换为Json");
        }
    }
}
